package com.ts.host;

import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMMessage;
import com.easemob.exceptions.EaseMobException;
import com.rio.core.L;
import com.rio.core.U;
import com.ts.host.Event.OpenWater;

import de.greenrobot.event.EventBus;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class CmdMessageReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		// 获取cmd message对象
		String msgId = intent.getStringExtra("msgid");


		EMMessage message = intent.getParcelableExtra("message");
		// 获取消息body
		CmdMessageBody cmdMsgBody = (CmdMessageBody) message.getBody();
		
		String userid  = message.getFrom();
		
		String aciton = cmdMsgBody.action;// 获取自定义action

		L.i(aciton);
		if (U.notNull(aciton) && "order".equals(aciton) 
				&& U.notNull(msgId) && U.notNull(userid)) {
			
			OpenWater event = new OpenWater();
			event.msgId = msgId;
			event.receipt = userid;
			// 获取扩展属性
			try {
				event.userID = message.getStringAttribute("userID");
				event.account = message.getIntAttribute("account");

			} catch (EaseMobException e) {
				L.e(e);
				return;
			}
			
			try {
				event.platform = message.getStringAttribute("platform");
			} catch (EaseMobException e) {
				L.e(e);
			}
			
			try {
				event.username = message.getStringAttribute("username");
			} catch (EaseMobException e) {
				L.e(e);
			}
			
			try {
				event.name = message.getStringAttribute("name");
			} catch (EaseMobException e) {
				L.e(e);
			}

			try {
				event.cuid = message.getStringAttribute("cuid");
			} catch (EaseMobException e) {
				L.e(e);
			}
			try {
				event.phone = message.getStringAttribute("phone");
			} catch (EaseMobException e) {
				L.e(e);
			}
			
			EventBus.getDefault().post(event);

		}
		
		
		if (U.notNull(aciton) && "dead".equals(aciton) 
				&& U.notNull(msgId) && U.notNull(userid)) {
			EventBus.getDefault().post(new Event.ScreenDark());
		}
		
		if (U.notNull(aciton) && "alive".equals(aciton) 
				&& U.notNull(msgId) && U.notNull(userid)) {
			EventBus.getDefault().post(new Event.ScreenBright());
		}
		
		if (U.notNull(aciton) && APP.TAG.equals(aciton) 
				&& U.notNull(msgId) && U.notNull(userid)) {
			Event.Debug test = new Event.Debug();
			test.receipt = userid;
			EventBus.getDefault().post(test);
		}
		
		if (U.notNull(aciton) && APP.TEST.equals(aciton) 
				&& U.notNull(msgId) && U.notNull(userid)) {
			Event.Test test = new Event.Test();
			EventBus.getDefault().post(test);
		}
	}

}
